package com.vincent.exception;

import com.alibaba.fastjson.JSON;
import com.vincent.common.enums.ResultMapKey;
import com.vincent.common.enums.SessionEnum;
import com.vincent.common.utils.RequestUtil;
import com.vincent.common.utils.SessionUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 集中异常处理类
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

    private static final Logger logger = Logger.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error("Error:", ex);
        ex.printStackTrace();
        boolean isAjax = RequestUtil.isAjax(request);
        ModelAndView modelAndView = new ModelAndView();

        HttpSession session = request.getSession();
        if (ex.getClass().equals(InValidParamException.class)) {
            String errorMsg = ex.getMessage();
            if(isAjax){
                Map<String,Object> map=new HashMap<String, Object>();
                map.put(ResultMapKey.ERROR.getCode(), errorMsg);
                try {
                    response.getWriter().println(JSON.toJSONString(map));
                } catch (IOException e) {
                    logger.error("Error:",e);
                }
                return modelAndView;
            }else{
                SessionUtil.clearSession(session);
                SecurityUtils.getSubject().logout();
                session=request.getSession();
                session.setAttribute(SessionEnum.ERRORMSG.getCode(), errorMsg);
                modelAndView.setViewName("redirect:/admin/login.html");
                return modelAndView;
            }
        }

        if(isAjax){
            Map<String,Object> map=new HashMap<String, Object>();
            map.put(ResultMapKey.ERROR.getCode(),"系统繁忙，请稍后再试");
            try {
                response.getWriter().println(JSON.toJSONString(map));
            } catch (IOException e) {
                logger.error("Error:",e);
            }
            return modelAndView;
        }
        SessionUtil.clearSession(session);
        SecurityUtils.getSubject().logout();
        modelAndView.setViewName("redirect:/error/500.html");
        return modelAndView;
    }
}
